package com.niit.bigdata.util;

import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class ResponseBuilder {

    private final ObjectMapper objectMapper;

    public ResponseBuilder(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    public void buildJsonResponse(HttpServletResponse response, Object data, int statusCode, String message) throws IOException {
        // 设置响应格式为 JSON
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(statusCode);

        // 构建全局响应格式
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("code", statusCode);
        responseData.put("data", data);
        responseData.put("message", message);

        // 将格式化后的响应写回客户端
        writeJsonResponse(response, responseData);
    }

    private void writeJsonResponse(HttpServletResponse response, Map<String, Object> responseData) throws IOException {
        try (PrintWriter writer = response.getWriter()) {
            objectMapper.writeValue(writer, responseData);
        }
    }
}